<?php

// 助手函数

if (!function_exists('is_ssl')) {
    /**
     * 判断是否SSL协议
     * @return boolean
     */
    function is_ssl()
    {
        if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) {
            return true;
        } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
            return true;
        }

        return false;
    }
}

if (!function_exists('get_host')) {
    /**
     * 返回带协议的域名
     * @return boolean
     */
    function get_host()
    {
        $host = $_SERVER['HTTP_HOST'];
        $protocol = is_ssl() ? 'https://' : 'http://';

        return $protocol . $host;
    }
}

if (!function_exists('get_IP')) {
    /**
     * 获取客户端IP
     * @return boolean
     */
    function get_IP()
    {
        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $ip = $_SERVER['REMOTE_ADDR'];
        } else {
            $ip = 'unknown';
        }

        return $ip;
    }
}

/**
 * 格式化字节大小  (用于数据库备份)
 *
 * @param number $size 字节数
 * @param string $delimiter 数字和单位分隔符
 * @return string 格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '')
{
    $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
    for ($i = 0; $size >= 1024 && $i < 5; $i++) {
        $size /= 1024;
    }

    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 转化数据库保存的文件路径为可以访问的url
 *
 * @param string $filepath
 * @return string
 */
function full_file_url($filepath)
{
    if ($filepath) {
        if (strpos($filepath, 'http') === 0 || strpos($filepath, 'https') === 0) {
            return $filepath;
        } else {
            $fullFileUrl = config('filesystems.disks.uploads.path') . $filepath;
            $fullFileUrl = str_replace('public/', '', $fullFileUrl);
            $fullFileUrl = asset($fullFileUrl);

            return $fullFileUrl;
        }
    } else {
        return asset('static/img/not_image.png');
    }
}

/**
 * 把返回的数据集转换成Tree
 *
 * @param array $list 要转换的数据集
 * @param string $pk 主键字段
 * @param string $pid parent标记字段
 * @param string $child
 * @param int $root
 * @param bool $isChild
 * @return array
 */
function list_to_tree($list, $pk = 'id', $pid = 'parent_id', $child = 'children', $root = 0, $isChild = false)
{
    // 创建Tree
    $tree = [];
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = [];
        foreach ($list as $key => $item) {
            $refer[$item[$pk]] = &$list[$key];
        }
        foreach ($list as $key => $item) {
            // 判断是否存在parent
            $parentId = $item[$pid];
            if ($root === $parentId) {
                if ($isChild && !isset($list[$key][$child])) {
                    $list[$key][$child] = []; // 子集为空
                }
                $tree[] = &$list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = &$refer[$parentId];
                    if ($isChild && !isset($list[$key][$child])) {
                        $list[$key][$child] = []; // 子集为空
                    }
                    $parent[$child][] = &$list[$key];
                }
            }
        }
    }

    return $tree;
}

if (!function_exists('api_response')) {
    /**
     * Api 统一返回格式
     * @return boolean
     */
    function api_response($status = 0, $msg = '', $data = [], $code = 200)
    {
        return response()->json([
            'status' => $status,
            'msg' => $msg,
            'data' => $data,
            'code' => $code
        ]);
    }
}
